package com.langll.ai.neo4j;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.langll.ai.AIChatApplication;
import com.langll.ai.neo4j.dao.portfolio.*;
import com.langll.ai.neo4j.node.FirstYear;
import com.langll.ai.neo4j.node.Portfolio;
import com.langll.ai.neo4j.node.Product;
import com.langll.ai.neo4j.relation.ContainPortfolio;
import com.langll.ai.neo4j.relation.ContainProduct;
import com.langll.ai.neo4j.relation.GenerateProduct;
import com.langll.ai.neo4j.relation.LastGenPortfolio;
import com.langll.ai.portfolio.mapper.PortfolioProductMapper;
import com.langll.ai.portfolio.model.PortfolioProduct;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.ArrayList;
import java.util.List;

/**
 * portfolio初始化创建关系
 */
@Slf4j
@SpringBootTest(classes = AIChatApplication.class)
@RunWith(SpringRunner.class)
public class PortfolioInitRelationship {
    @Autowired
    private GenerateProductRepository generateProductRepository;
    @Autowired
    private LastGenPortfolioRepository lastGenPortfolioRepository;
    @Autowired
    private LifecycleExtendPortfolioRepository lifecycleExtendPortfolioRepository;
    @Autowired
    private PortfolioRepository portfolioRepository;
    @Autowired
    private ProductRepository productRepository;

    @Autowired
    private PortfolioProductMapper portfolioProductMapper;

    @Test
    public void initPortfolio(){
        queryPortfolios()
                .forEach(portfolioProduct -> {
                    // 生成portfolio
                    Portfolio portfolioNode = new Portfolio();
                    portfolioNode.setId(portfolioProduct.getId().longValue());
                    portfolioNode.setName(portfolioProduct.getProductName());
                    portfolioNode.setMasterId(portfolioProduct.getMasterId());

                    List<GenerateProduct> generateProducts = new ArrayList<>();
                    // 生成关联的 product
                    List<PortfolioProduct> products =  queryProductsByPortfolio(portfolioProduct.getId());
                    products.forEach(product -> {
                        // 生成product
                        Product productNode = new Product();
                        productNode.setId(product.getId().longValue());
                        productNode.setName(product.getProductName());
                        productNode.setMasterId(product.getMasterId());

                        // 生成portfolio和product的关系
                        GenerateProduct generateProduct = new GenerateProduct();
                        generateProduct.setProduct(productNode);
                        if (product.getPrimaryProduct()) {
                            generateProduct.setType(GenerateProduct.ProductType.PRIMARY);
                        } else {
                            generateProduct.setType(GenerateProduct.ProductType.SECONDARY);
                        }
                        generateProducts.add(generateProduct);
                    });

                    // 生成portfolio和lastGenPortfolio的关系
                    List<PortfolioProduct> lastGenPortfolioByPortfolio = queryLastGenPortfolioByPortfolio(portfolioProduct.getProductName());
                    List<LastGenPortfolio> lastGenPortfolios = new ArrayList<>();
                    lastGenPortfolioByPortfolio.forEach(lastGenPortfolio -> {
                        Portfolio lastGenPortfolioNode = new Portfolio();
                        lastGenPortfolioNode.setId(lastGenPortfolio.getId().longValue());
                        lastGenPortfolioNode.setName(lastGenPortfolio.getProductName());
                        lastGenPortfolioNode.setMasterId(lastGenPortfolio.getMasterId());

                        // 生成portfolio和lastGenPortfolio的关系
                        LastGenPortfolio lastGenPortfolioRelation = new LastGenPortfolio();
                        lastGenPortfolioRelation.setPortfolio(lastGenPortfolioNode);
                        lastGenPortfolios.add(lastGenPortfolioRelation);
                    });

                    portfolioNode.setLastGenPortfolios(lastGenPortfolios);
                    portfolioNode.setGenerateProducts(generateProducts);
                    portfolioRepository.save(portfolioNode);
                });
    }

    @Autowired
    private FirstYearRepository firstYearRepository;
    @Test
    public void initFirstYear(){
        List<String> fiscalYears = portfolioProductMapper.getAllFiscalYear();
        fiscalYears.forEach(fiscalYear->{
            int[] years = extractYears(fiscalYear);
            log.info("fiscalYear: {}", years[0]);

            FirstYear firstYearNode = new FirstYear();
            firstYearNode.setId(Long.valueOf(years[0]));
            firstYearNode.setName(fiscalYear);

            //查询fy 对应的所有的portfolio, 并将其添加到firstYear的图关系中
            List<PortfolioProduct> portfolios = queryPortfoliosByFY(fiscalYear);
            List<ContainPortfolio> containPortfolios = new ArrayList<>();
            portfolios.forEach(portfolioProduct -> {
                ContainPortfolio containPortfolio = new ContainPortfolio();
                // 生成portfolio
                Portfolio portfolioNode = new Portfolio();
                portfolioNode.setId(portfolioProduct.getId().longValue());
                portfolioNode.setName(portfolioProduct.getProductName());
                portfolioNode.setMasterId(portfolioProduct.getMasterId());

                containPortfolio.setPortfolio(portfolioNode);
                containPortfolios.add(containPortfolio);
            });
            firstYearNode.setContainPortfolios(containPortfolios);

            //查询fy 对应的所有的product, 并将其添加到firstYear的图关系中
            List<PortfolioProduct> products = queryProductsByFY(fiscalYear);
            List<ContainProduct> ContainProducts = new ArrayList<>();
            products.forEach(portfolioProduct -> {
                ContainProduct containProduct = new ContainProduct();
                // 生成portfolio
                Product productNode = new Product();
                productNode.setId(portfolioProduct.getId().longValue());
                productNode.setName(portfolioProduct.getProductName());
                productNode.setMasterId(portfolioProduct.getMasterId());

                containProduct.setProduct(productNode);
                ContainProducts.add(containProduct);
            });

            firstYearNode.setContainProducts(ContainProducts);
            firstYearRepository.save(firstYearNode);
        });
    }
    @Test
    public void testUpdatePortfolio(){
        Portfolio portfolioNode = new Portfolio();
        portfolioNode.setId(16646L);
        portfolioNode.setName("Cry0-QyYWL");
        portfolioNode.setMasterId("PRD20180905_0189");
        portfolioRepository.save(portfolioNode);
    }


    @Autowired
    private ContainProductRepository containProductRepository;
    @Autowired
    private ContainPortfolioRepository containPortfolioRepository;

    @Test
    public void deletePortfolio(){
//        portfolioRepository.deleteAll();
//        productRepository.deleteAll();
        firstYearRepository.deleteAll();
//        containPortfolioRepository.deleteAll();
//        containProductRepository.deleteAll();
    }

    public int[] extractYears(String fiscalYear) {
        // 使用正则表达式匹配年份
        if(fiscalYear == null || !fiscalYear.startsWith("FY")) {
            throw new IllegalArgumentException("Invalid fiscal year format: " + fiscalYear);
        }
        String[] years = fiscalYear.replace("FY", "").trim().split("/");
        int startYear = Integer.parseInt(years[0].trim());
        int endYear = Integer.parseInt(years[1].trim());
        return new int[]{startYear, endYear};
    }

    public List<PortfolioProduct> queryPortfolios() {
        QueryWrapper<PortfolioProduct> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(PortfolioProduct::getMain,1)//main = 1 portfolio
                .eq(PortfolioProduct::getDeleteFlag,0)
                .eq(PortfolioProduct::getLatestversion,1);
        return portfolioProductMapper.selectList(queryWrapper);
    }

    public List<PortfolioProduct> queryPortfoliosByFY(String fiscalYear) {
        QueryWrapper<PortfolioProduct> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(PortfolioProduct::getMain,1)//main = 1 portfolio
                .eq(PortfolioProduct::getDeleteFlag,0)
                .eq(PortfolioProduct::getLatestversion,1)
                .eq(PortfolioProduct::getPlanningCycle, fiscalYear);
        return portfolioProductMapper.selectList(queryWrapper);
    }

    public List<PortfolioProduct> queryProducts() {
        QueryWrapper<PortfolioProduct> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(PortfolioProduct::getMain,0)// main = 0 product
                .eq(PortfolioProduct::getDeleteFlag,0)
                .eq(PortfolioProduct::getLatestversion,1);
        return portfolioProductMapper.selectList(queryWrapper);
    }

    public List<PortfolioProduct> queryProductsByFY(String fiscalYear) {
        QueryWrapper<PortfolioProduct> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(PortfolioProduct::getMain,0)// main = 0 product
                .eq(PortfolioProduct::getDeleteFlag,0)
                .eq(PortfolioProduct::getLatestversion,1)
                .eq(PortfolioProduct::getPlanningCycle, fiscalYear);
        return portfolioProductMapper.selectList(queryWrapper);
    }

    public List<PortfolioProduct> queryProductsByPortfolio(Integer portfolioId) {
        QueryWrapper<PortfolioProduct> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(PortfolioProduct::getMain,0)// main = 0 product
                .eq(PortfolioProduct::getDeleteFlag,0)
                .eq(PortfolioProduct::getLatestversion,1)
                .eq(PortfolioProduct::getParentId, portfolioId);
        return portfolioProductMapper.selectList(queryWrapper);
    }
    public List<PortfolioProduct> queryLastGenPortfolioByPortfolio(String portfolioName) {
        QueryWrapper<PortfolioProduct> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(PortfolioProduct::getMain,0)// main = 0 product
                .eq(PortfolioProduct::getDeleteFlag,0)
                .eq(PortfolioProduct::getLatestversion,1)
                .eq(PortfolioProduct::getLastGenProduct, portfolioName);
        return portfolioProductMapper.selectList(queryWrapper);
    }

}
